package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.user.config.MailConfig;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserRegisterRequest;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.service.IUserRegisterService;
import org.apache.logging.log4j.message.StringFormattedMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Bowen Deng
 * @since 2022/07/08 23:54
 */
@Service
public class UserRegisterServiceImpl implements IUserRegisterService {
    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    MailConfig mailConfig;

    @Autowired
    JavaMailSender sender;

    @Override
    public UserRegisterResponse userRegister(UserRegisterRequest request) {
        UserRegisterResponse response = new UserRegisterResponse();

        try {
            //验证
            request.requestCheck();
            Example example = new Example(Member.class);
            example.createCriteria()
                    .andEqualTo("username", request.getUserName());
            List<Member> members = memberMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(members)) {
                response.setCode(UserRetCode.USERNAME_ALREADY_EXISTS.getCode());
                response.setMsg(UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
            }
            //插入
            //1.Member
            Member member = new Member();
            member.setUsername(request.getUserName());
            member.setPassword(DigestUtils.md5DigestAsHex(request.getUserPwd().getBytes()));
            member.setCreated(new Date());
            member.setEmail(request.getEmail());
            member.setUpdated(new Date());
            member.setIsVerified("N");
            member.setState(1);
            int affectedRows = memberMapper.insert(member);
            if (affectedRows != 1) {
                response.setCode(UserRetCode.USER_REGISTER_FAILED.getCode());
                response.setMsg(UserRetCode.USER_REGISTER_FAILED.getMessage());
                return response;
            }
            //2.UserVerify
            UserVerify userVerify = new UserVerify();
            userVerify.setUsername(member.getUsername());
            String key = member.getUsername() + member.getPassword() + UUID.randomUUID().toString();
            String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
            userVerify.setUuid(uuid);
            userVerify.setRegisterDate(new Date());
            userVerify.setIsVerify("N");
            userVerify.setIsExpire("N");
            int affectedRow = userVerifyMapper.insert(userVerify);
            if (affectedRow != 1) {
                response.setCode(UserRetCode.USER_REGISTER_VERIFY_FAILED.getCode());
                response.setMsg(UserRetCode.USER_REGISTER_VERIFY_FAILED.getMessage());
                return response;
            }
            // 发送邮件
            // TODO 应该并发实现，可以创建线程，后面会学习消息队列 MQ 用它实现
            new Thread(() -> sendMail(uuid, request)).start();

            //执行成功
            response.setCode(UserRetCode.SUCCESS.getCode());
            response.setMsg(UserRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * 用于发送邮件
     *
     * @param uuid
     * @param request
     * @return void
     * @author Can
     * @since 2022/07/09 10:18
     */
    private void sendMail(String uuid, UserRegisterRequest request) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(request.getEmail());
        message.setFrom(mailConfig.getUsername());
        message.setSubject(mailConfig.getSubject());
        message.setText(String.format(mailConfig.getText(), request.getUserName(), uuid));
        sender.send(message);
    }
}
